import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../models/note.dart';
import '../repositories/note_repository.dart';
import 'dart:io';
import '../widgets/image_preview_widget.dart';

class NoteListScreen extends StatefulWidget {
  const NoteListScreen({super.key});

  @override
  State<NoteListScreen> createState() => _NoteListScreenState();
}

class _NoteListScreenState extends State<NoteListScreen> {
  final _noteRepository = NoteRepository();
  bool _isLoading = true;
  List<Note> _notes = [];
  String? _selectedCategory;
  final List<String> _categories = [
    '全部',
    '时政', 
    '常识判断', 
    '言语理解与表达', 
    '数量关系', 
    '判断推理', 
    '资料分析'
  ];
  
  @override
  void initState() {
    super.initState();
    _loadNotes();
  }
  
  Future<void> _loadNotes() async {
    setState(() => _isLoading = true);
    
    try {
      List<Note> notes;
      if (_selectedCategory == null || _selectedCategory == '全部') {
        notes = await _noteRepository.getAllNotes();
      } else {
        notes = await _noteRepository.getNotesByCategory(_selectedCategory!);
      }
      
      setState(() {
        _notes = notes;
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      _showErrorSnackBar('加载笔记失败: $e');
    }
  }
  
  void _deleteNote(int id) async {
    try {
      await _noteRepository.deleteNote(id);
      
      // 重新加载笔记列表
      _loadNotes();
      
      _showSuccessSnackBar('笔记已删除');
    } catch (e) {
      _showErrorSnackBar('删除笔记失败: $e');
    }
  }
  
  void _showDeleteConfirmDialog(int id) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除笔记', style: TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])),
        content: const Text('确定要删除这条笔记吗？此操作不可撤销。', style: TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消', style: TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _deleteNote(id);
            },
            child: const Text('删除', style: TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
          ),
        ],
      ),
    );
  }
  
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message, style: const TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312']))),
    );
  }
  
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message, style: const TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])),
        backgroundColor: Colors.red,
      ),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的笔记', style: TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])),
        centerTitle: true,
      ),
      body: Column(
        children: [
          // 分类筛选器
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: _categories.map((category) {
                  final isSelected = _selectedCategory == category || 
                      (category == '全部' && _selectedCategory == null);
                  return Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 4.0),
                    child: FilterChip(
                      label: Text(category, style: const TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])),
                      selected: isSelected,
                      onSelected: (selected) {
                        setState(() {
                          _selectedCategory = selected 
                              ? (category == '全部' ? null : category)
                              : null;
                        });
                        _loadNotes();
                      },
                    ),
                  );
                }).toList(),
              ),
            ),
          ),
          
          // 笔记列表
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _notes.isEmpty
                    ? Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            const Icon(Icons.note_alt_outlined, size: 64, color: Colors.grey),
                            const SizedBox(height: 16),
                            Text(
                              _selectedCategory == null || _selectedCategory == '全部'
                                  ? '暂无笔记'
                                  : '暂无${_selectedCategory}分类的笔记',
                              style: const TextStyle(fontSize: 18, color: Colors.grey, fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])
                            ),
                            const SizedBox(height: 24),
                          ],
                        ),
                      )
                    : ListView.builder(
                        itemCount: _notes.length,
                        itemBuilder: (context, index) {
                          final note = _notes[index];
                          return Card(
                            margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                            child: InkWell(
                              onTap: () async {
                                final result = await context.push('/profile/notes/edit/${note.id}');
                                if (result == true) {
                                  _loadNotes();
                                }
                              },
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  // 图片预览（如果有）
                                  if (note.imageUrl != null && note.imageUrl!.isNotEmpty)
                                    SizedBox(
                                      height: 150,
                                      width: double.infinity,
                                      child: _buildNoteImage(note.imageUrl!),
                                    ),
                                  
                                  Padding(
                                    padding: const EdgeInsets.all(12.0),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          children: [
                                            Expanded(
                                              child: Text(
                                                note.title,
                                                style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16, fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312']),
                                              ),
                                            ),
                                            IconButton(
                                              icon: const Icon(Icons.delete_outline, size: 20),
                                              onPressed: () => _showDeleteConfirmDialog(note.id!),
                                              padding: EdgeInsets.zero,
                                              constraints: const BoxConstraints(),
                                            ),
                                          ],
                                        ),
                                        const SizedBox(height: 8),
                                        Text(
                                          note.content,
                                          maxLines: 2,
                                          overflow: TextOverflow.ellipsis,
                                          style: const TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312']),
                                        ),
                                        const SizedBox(height: 8),
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            Chip(
                                              label: Text(note.category, style: const TextStyle(fontSize: 12, fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])),
                                              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                              padding: EdgeInsets.zero,
                                            ),
                                            Text(
                                              '更新于: ${_formatDate(DateTime.fromMillisecondsSinceEpoch(note.updated_at))}',
                                              style: TextStyle(fontSize: 12, color: Colors.grey[600], fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312']),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          final result = await context.push('/profile/notes/add');
          if (result == true) {
            _loadNotes();
          }
        },
        child: const Icon(Icons.add),
      ),
    );
  }
  
  Widget _buildNoteImage(String imageUrl) {
    return ImagePreviewWidget(
      imageUrl: imageUrl,
      height: 150,
      width: double.infinity,
      fit: BoxFit.contain,
      showPath: false,
    );
  }
  
  String _formatDate(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')}';
  }
}